package com.example.tangjiangxu.viewtest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class CounterView extends View {
    private Paint paint;
    private Rect mBounds;

    private int count;

    public CounterView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        mBounds = new Rect();
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                count ++;
                invalidate();
            }
        });
    }

    /**
     * 绘制调用的方法
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.GREEN);
        canvas.drawRect(0, 0, getWidth(), getHeight(), paint);

        paint.setColor(Color.RED);
        paint.setTextSize(50);
        String text = count + "";
        paint.getTextBounds(text, 0, text.length(), mBounds);
        canvas.drawText(text, getWidth() / 2 -mBounds.width() / 2, getHeight() / 2 + mBounds.height() / 2, paint);
    }

}
